package com.lzy.webapi.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.base.apis.SysUserAdminServiceApi;
import com.lzy.base.apis.SysUserIdentityServiceApi;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.dtos.SysUserIdentityDto;
import com.lzy.common.apis.AreaServiceApi;
import com.lzy.common.apis.ShopServiceApi;
import com.lzy.common.apis.StoreServiceApi;
import com.lzy.common.constants.BusinessType;
import com.lzy.common.dtos.AreaDto;
import com.lzy.common.dtos.ShopSaveDto;
import com.lzy.common.dtos.StoreDto;
import com.lzy.coupon.apis.MotorcycleServiceApi;
import com.lzy.coupon.apis.MotorcycleSpecServiceApi;
import com.lzy.coupon.dtos.MotorcycleDto;
import com.lzy.coupon.dtos.MotorcycleSpecDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.tools.commons.BigDecimalUtil;
import com.lzy.framework.tools.date.DateUtils;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.member.apis.MemberSaleLogServiceApi;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberSaleLogDto;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.member.entity.MemberUser;
import com.lzy.order.apis.OrderApi;
import com.lzy.order.constants.CommonConstants;
import com.lzy.order.constants.OrderSatusDesEnum;
import com.lzy.order.dtos.OrderShowShopDTO;
import com.lzy.order.dtos.coupon.MotorSaleDTO;
import com.lzy.order.dtos.coupon.OrderInfoMotorCouponDTO;
import com.lzy.order.service.SerialNumberService;
import com.lzy.payment.apis.PayApi;
import com.lzy.payment.dtos.pay.CommonPayDTO;
import com.lzy.product.apis.*;
import com.lzy.product.constants.OrderBusiConstants;
import com.lzy.product.dtos.*;
import com.lzy.product.dtos.agent.AgentOrderInfoDto;
import com.lzy.product.dtos.agent.AgentOrderSalesRecordDto;
import com.lzy.sms.apis.MsgCodeApi;
import com.lzy.sms.constants.BusiTypeEnum;
import com.lzy.sms.dtos.CodeDTO;
import com.lzy.sms.dtos.SendSmsDTO;
import com.lzy.webapi.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by WIN7 on 2017/12/05.
 */
@Component
public class OrderFacade {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderFacade.class);

    @Autowired
    private OrderProductImageServiceApi orderProductImageServiceApi;

    @Autowired
    private OrderProductServiceApi orderProductServiceApi;

    @Autowired
    private ProductInfoServiceApi productInfoServiceApi;

    @Autowired
    private MemberUserServiceApi memberUserServiceApi;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private MsgCodeApi msgCodeApi;

    @Autowired
    private ProductInfoProjectServiceApi productInfoProjectServiceApi;

    @Autowired
    private OrderProjectRecordServiceApi orderProjectRecordServiceApi;

    @Autowired
    private ProductClassifyServiceApi productClassifyServiceApi;

    @Autowired
    private OrderPayCodeServiceApi orderPayCodeServiceApi;

    @Autowired
    private AreaServiceApi areaServiceApi;

    @Autowired
    private SysUserAdminServiceApi sysUserAdminServiceApi;

    @Autowired
    private SysUserIdentityServiceApi sysUserIdentityServiceApi;

    @Autowired
    private ProductYieldRatioServiceApi productYieldRatioServiceApi;

    @Autowired
    private OrderYieldRatioServiceApi orderYieldRatioServiceApi;

    @Autowired
    private ShopServiceFacade shopServiceFacade;

    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;
    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;
    @Autowired
    private StoreServiceApi storeServiceApi;

    @Autowired
    private PayApi payApi;

    @Autowired
    private KvClient kvClient;

    @Autowired
    private MemberSaleLogServiceApi memberSaleLogServiceApi;

    @Autowired
    private ProductUserServiceApi productUserServiceApi;

    @Autowired
    private OrderApi orderApi;

    @Autowired
    private MotorcycleSpecServiceApi motorcycleSpecServiceApi;

    @Autowired
    private ShopServiceApi shopServiceApi;

    @Autowired
    private MotorcycleServiceApi motorcycleServiceApi;

    @Autowired
    private AgentOrderInfoServiceApi agentOrderInfoServiceApi;

    /**
     * 发送验证码
     *
     * @param phone
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_COMMON)
    public Boolean generateCode(String phone) {
        Ensure.that(phone).isNotNull("04000001");
        //发送短信目标
        SendSmsDTO ssDTO = new SendSmsDTO();
        ssDTO.setAuthTarget(phone);
        //业务类型
        ssDTO.setAuthType(BusiTypeEnum.PRODUCT_ORDER_VERIFY.getVal());
        //媒介类型
        ssDTO.setWay(com.lzy.sms.constants.CommonConstants.MediaWay.PHONE);
        //发送验证码
        return msgCodeApi.sendCode(ssDTO, null);
    }

    /**
     * 验证码验证
     *
     * @param codeDTO
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_COMMON)
    public Boolean verifyAuthInfo(CodeDTO codeDTO) {
        return msgCodeApi.verifyAuthInfo(codeDTO);
    }

    /**
     * 生成产品订单
     *
     * @param orderProductDto
     * @return
     */
    public OrderProductDto createOrderProduct(OrderProductDto orderProductDto) {
        if (orderProductDto == null) {
            return null;
        }
        switch (orderProductDto.getType() + "") {
            case OrderBusiConstants.Biz.PRODUCT: {
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                //减掉产品分类对应的库存量
                if (orderProductDto.getCount() == null)
                    orderProductDto.setCount(1);
                Ensure.that(productClassifyServiceApi.updateSurplusByProductId(orderProductDto.getProductId(), orderProductDto.getCount(), "-")).isTrue("04000010");
                Date expiredDate = DateUtils.addMinutes(new Date(), 4320);
                orderProductDto.setExpiredTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDate));
                orderProductDto.setCount(1);
                ProductInfoDto productInfo = productInfoServiceApi.findById(orderProductDto.getProductId());
                if (productInfo != null) {
                    orderProductDto.setMoneyCount(productInfo.getPrice());
                    orderProductDto.setProductName(productInfo.getName());
                    orderProductDto.setProductImage(productInfo.getCover());
                }
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                orderProductDto.setOrderId(serialNumberService.createSerialNumber(CommonConstants.Biz.PRODUCT, orderProductDto.getCreateUser().toString()));
                //没有会员信息则添加
                MemberUserDto memberUserDto = findMembersByMobile(orderProductDto.getPhone());
                if (memberUserDto == null) {
                    memberUserDto = new MemberUserDto();
                    memberUserDto.setAccount(orderProductDto.getMemberAccount());
                    memberUserDto.setName(orderProductDto.getMemberName());
                    MemberUserDto member = createMember(memberUserDto);
                    Ensure.that(member).isNotNull("04000003");
                    orderProductDto.setMemberId(member.getId());
                    orderProductDto.setMemberCondition(1);//没有注册
                    //发送短信
                    SendSmsDTO sendSmsDTO = new SendSmsDTO();
                    sendSmsDTO.setAuthTarget(orderProductDto.getMemberAccount());
                    sendSmsDTO.setAuthType(BusiTypeEnum.PRODUCT_REGISTER_SUCCESS.getVal());
                    sendSmsDTO.setWay(com.lzy.sms.constants.CommonConstants.MediaWay.PHONE);
                    Map<String, Object> map = new HashMap<>();
                    map.put("password", "111111");
                    map.put("address", "http://wp.lzyhll.com/app/appld.html");
                    msgCodeApi.sendCode(sendSmsDTO, null);
                } else {
                    orderProductDto.setMemberId(memberUserDto.getId());
                    orderProductDto.setMemberCondition(2);//仅注册了会员
                    SysUserAdminDto sysUserAdminDto = sysUserAdminServiceApi.selectByPhone(orderProductDto.getPhone());
                    if (sysUserAdminDto != null) {
                        if (productInfo != null && productInfo.getIdentityId() != null && !productInfo.getIdentityId().equals(0)) {
                            List<SysUserIdentityDto> identityList = sysUserIdentityServiceApi.selectByUserId(sysUserAdminDto.getId());
                            for (SysUserIdentityDto identity : identityList) {
                                if (productInfo.getIdentityId().equals(identity.getIdentityId())) {
                                    orderProductDto.setMemberCondition(3);//注册并且拥有产品对应的身份
                                }
                            }
                        }
                    }
                }
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                Long orderId = orderProductServiceApi.insert(orderProductDto);
                Ensure.that(orderId).isGt(0, "04000002");
                //添加订单与产品包含项的关系
                //获取产品套餐内容（固定项）进行添加
                List<ProductInfoProjectDto> packages = new ArrayList<>();//产品套餐内容
                ProductInfoDto productInfoDto = productInfoServiceApi.getProductProject(orderProductDto.getProductId());
                if (productInfoDto != null) {
                    if (productInfoDto.getProjectList() != null && productInfoDto.getProjectList().size() > 0) {
                        for (ProductInfoProjectDto pipd : productInfoDto.getProjectList()) {
                            if (pipd.getType() != null && pipd.getType().equals(0)) {
                                packages.add(pipd);
                            }
                        }
                    }
                }
                for (ProductInfoProjectDto project : packages) {
                    Ensure.that(addOrderProjectRecord(orderProductDto.getOrderId(), project)).isTrue("04000008");
                }
                //获取产品套餐内容（单选项）进行添加
                ProductInfoProjectDto productInfoProjectDto = new ProductInfoProjectDto();
                productInfoProjectDto.setProductId(orderProductDto.getProductId());
                productInfoProjectDto.setProjectId(orderProductDto.getProjectId());
                productInfoProjectDto.setType(1);
                List<ProductInfoProjectDto> list = productInfoProjectServiceApi.query(productInfoProjectDto);
                if (list != null && list.size() > 0) {
                    Ensure.that(list.size()).isEqual(1, "04000007");
                    ProductInfoProjectDto project = list.get(0);
                    Ensure.that(addOrderProjectRecord(orderProductDto.getOrderId(), project)).isTrue("04000008");
                }
                kvClient.add2Zset("zset:queue:product:order:paytime", expiredDate.getTime(), orderProductDto.getOrderId()); //放入缓存中
                break;
            }
            case OrderBusiConstants.Biz.COUPONS: {
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                //减掉产品分类对应的库存量
                if (orderProductDto.getCount() == null)
                    orderProductDto.setCount(1);
                Date expiredDate = DateUtils.addMinutes(new Date(), 4320);
                orderProductDto.setExpiredTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expiredDate));
                orderProductDto.setCount(1);
                ProductInfoDto productInfo = productInfoServiceApi.findById(orderProductDto.getProductId());
                if (productInfo != null) {
                    orderProductDto.setMoneyCount(productInfo.getPrice());
                    orderProductDto.setProductName(productInfo.getName());
                    orderProductDto.setProductImage(productInfo.getCover());
                    orderProductDto.setLimitTime(productInfo.getLimitTime());
                }
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                orderProductDto.setOrderId(serialNumberService.createSerialNumber(CommonConstants.Biz.PRODUCT, orderProductDto.getCreateUser().toString()));
                //创建商户用户
                ShopSaveDto shopSaveDto = new ShopSaveDto();
                shopSaveDto.setCategoryId(BusinessType.ShopType.SALE_MAN.getCode());
                shopSaveDto.setName(orderProductDto.getName());
                shopSaveDto.setContact(orderProductDto.getPhone());
                shopSaveDto.setIdCardNo(orderProductDto.getIdCard());
                shopSaveDto.setModules(BusinessType.ShopType.SALE_MAN.getCode().toString());
                shopSaveDto.setLinkMan(orderProductDto.getName());
                shopSaveDto.setShopAppId(BusinessType.ShopType.SALE_MAN.getCode().toString());
                shopServiceFacade.saveShop(shopSaveDto);
                //查询会员信息
                MemberUserDto memberUserDto = findMembersByMobile(orderProductDto.getPhone());
                DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
                orderProductDto.setMemberId(memberUserDto.getId());
                Long orderId = orderProductServiceApi.insert(orderProductDto);
                Ensure.that(orderId).isGt(0, "04000002");
                //获取产品套餐内容进行添加
                ProductInfoProjectDto productInfoProjectDto = new ProductInfoProjectDto();
                productInfoProjectDto.setProductId(orderProductDto.getProductId());
                List<ProductInfoProjectDto> list = productInfoProjectServiceApi.query(productInfoProjectDto);
                if (list != null && list.size() > 0) {
                    for (ProductInfoProjectDto project : list) {
                        Boolean flag = addOrderProjectRecord(orderId, project);
                        Ensure.that(flag).isTrue("04000008");
                    }
                }
                //添加订单与产品收益比率关联关系
                ProductYieldRatioDto productYieldRatioDto = productYieldRatioServiceApi.findById(orderProductDto.getYieldRatioId());
                Boolean ok = addOrderYieldRatio(orderId, memberUserDto.getId(), orderProductDto, productYieldRatioDto);
                Ensure.that(ok).isTrue("04000012");
                MemberCouponsDto memberCouponsDto = new MemberCouponsDto();
                memberCouponsDto.setMemberId(memberUserDto.getId());
                memberCouponsServiceApi.updateMemberCoupons(memberCouponsDto);
                kvClient.add2Zset("zset:queue:product:order:paytime", expiredDate.getTime(), orderProductDto.getOrderId()); //放入缓存中
                break;
            }
        }
        return orderProductDto;
    }

    /**
     * 添加订单与产品包含项的关系
     *
     * @param orderId 订单号
     * @param project 包含项详情对象
     * @return
     */

    private Boolean addOrderProjectRecord(Long orderId, ProductInfoProjectDto project) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderProjectRecordDto orderProjectRecordDto = new OrderProjectRecordDto();
        orderProjectRecordDto.setOrderId(orderId);
        orderProjectRecordDto.setProjectId(project.getProjectId());
        orderProjectRecordDto.setCount(project.getContainNum());
        orderProjectRecordDto.setPrice(project.getPrice());
        orderProjectRecordDto.setType(project.getType());
        orderProjectRecordDto.setValidTime(project.getValidTime());
        orderProjectRecordDto.setProjectType(project.getProjectType());
        return orderProjectRecordServiceApi.insert(orderProjectRecordDto);
    }


    /**
     * 新增订单收益比率信息
     *
     * @param orderId
     * @param memberId
     * @param orderProductDto
     * @param productYieldRatioDto
     * @return
     */
    private Boolean addOrderYieldRatio(Long orderId, Long memberId,
                                       OrderProductDto orderProductDto,
                                       ProductYieldRatioDto productYieldRatioDto) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderYieldRatioDto dto = new OrderYieldRatioDto();
        dto.setProductId(orderProductDto.getProductId());
        dto.setOrderId(orderId);
        dto.setMemberId(memberId);
        BigDecimal totalDragon = BigDecimalUtil.to2Point(BigDecimalUtil.multiply(orderProductDto.getMoneyCount(), BigDecimalUtil.add(BigDecimalUtil.divide(productYieldRatioDto.getCashbackRatio(), new BigDecimal("100")), BigDecimal.ONE)));
        dto.setPrice(totalDragon);
        BigDecimal dailyIncome = couponProfitRecordServiceApi.calculateDayProfit(totalDragon, productYieldRatioDto.getCashbackTime());
        //10元代理商每天分不到0.01，特殊处理为0.01（18-3-27）
        if (orderProductDto.getMoneyCount() != null && orderProductDto.getMoneyCount().intValue() == 10) {
            dto.setDailyIncome(new BigDecimal(0.01));
        } else {
            dto.setDailyIncome(dailyIncome);
        }
        dto.setCashbackRatio(productYieldRatioDto.getCashbackRatio());
        dto.setCashbackTime(productYieldRatioDto.getCashbackTime());
        dto.setLimitTime(orderProductDto.getLimitTime());
        return orderYieldRatioServiceApi.createOrderYieldRatio(dto);
    }

    /**
     * 获取支付二维码地址
     *
     * @return
     */
    public OrderProductDto payCode(OrderProductDto orderProductDto) {
        Ensure.that(orderProductDto).isNotNull("04000001");
        Ensure.that(orderProductDto.getOrderId()).isNotNull("04000001");
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        CommonPayDTO commonPayDTO = new CommonPayDTO();
        commonPayDTO.setSerialNumber(orderProductDto.getOrderId().toString());
        commonPayDTO.setType(5);
        commonPayDTO.setWay(orderProductDto.getPayWay());
        OrderProductDto orderProduct = orderProductServiceApi.findById(orderProductDto.getOrderId());
        if (orderProduct.getProductId() != null && !"".equals(orderProduct.getProductId())) {
            ProductInfoDto productInfoDto = productInfoServiceApi.findById(orderProduct.getProductId());
            if (productInfoDto != null && productInfoDto.getName() != null) {
                commonPayDTO.setSkuName(productInfoDto.getName());
            }
        } else {
            commonPayDTO.setSkuName("龙之游产品");
        }
        commonPayDTO.setAmount(orderProduct.getMoneyCount());
        commonPayDTO.setUserId(orderProduct.getMemberId());
        OrderPayCodeDto orderPayCodeDto = checkPayCode(orderProductDto.getOrderId(), orderProductDto.getPayWay());
        if (orderPayCodeDto != null) {
            orderProductDto.setPayCode(orderPayCodeDto.getCodeUrl());
        } else {
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            Map map = payApi.scanCodePayRequest(commonPayDTO);
            String payCode = (String) map.get("code_url");
            Ensure.that(payCode).isNotBlank("04000009");
            orderProductDto.setPayCode(payCode);
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
            OrderPayCodeDto payCodeDto = new OrderPayCodeDto();
            payCodeDto.setOrderId(orderProductDto.getOrderId());
            payCodeDto.setPayWay(orderProductDto.getPayWay());
            payCodeDto.setCodeUrl(orderProductDto.getPayCode());
            Ensure.that(orderPayCodeServiceApi.insert(payCodeDto)).isGt(0, "04000011");
        }
        orderProductDto.setMoneyCount(orderProduct.getMoneyCount());
        return orderProductDto;
    }

    private OrderPayCodeDto checkPayCode(Long orderId, Integer payWay) {
        OrderPayCodeDto orderPayCodeDto = new OrderPayCodeDto();
        orderPayCodeDto.setOrderId(orderId);
        orderPayCodeDto.setPayWay(payWay);
        List<OrderPayCodeDto> list = orderPayCodeServiceApi.selectList(orderPayCodeDto);
        if (list != null) {
            if (list.size() == 1) {
                return list.get(0);
            }
        }
        return null;
    }

    public Map createCommonPayRequest(CommonPayDTO commonPayDTO) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderProductDto orderProductDto = orderProductServiceApi.findById(Long.parseLong(commonPayDTO.getSerialNumber()));
        if (orderProductDto != null) {
            commonPayDTO.setAmount(orderProductDto.getMoneyCount());
        }
        if (commonPayDTO.getSkuName() == null || "".equals(commonPayDTO.getSkuName())) {
            commonPayDTO.setSkuName("龙之游产品");
        }
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        Map map = payApi.createCommonPayRequest(commonPayDTO);
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        return map;
    }

    @DataSource(name = DataSource.DATASOURCE_COMMON)
    private MemberUserDto createMember(MemberUserDto memberUserDto) {
        return memberUserServiceApi.addMember(memberUserDto);
    }

    @DataSource(name = DataSource.DATASOURCE_COMMON)
    private MemberUserDto findMembersByMobile(String account) {
        return memberUserServiceApi.findMemberByMobile(account);
    }

    /**
     * 编辑产品订单
     *
     * @param orderProductDto
     * @return
     */
    public Boolean updateOrderProduct(OrderProductDto orderProductDto) {
        return orderProductServiceApi.update(orderProductDto);
    }

    /**
     * 查询产品订单列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_PRODUCT)
    public PageInfo orderProductList(Pager pager, OrderProductDto orderProductDto) {
        return orderProductServiceApi.selectList(pager, orderProductDto);
    }

    /**
     * 查看订单详情
     *
     * @param orderId
     * @return
     */
    public OrderProductDetailResponse orderProductDetail(Long orderId) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderProductDto orderProductDto = orderProductServiceApi.findById(orderId);
        //附加信息
        if (null != orderProductDto) {
            //线下打款凭证信息
            List<OrderProductImageDto> list = orderProductImageServiceApi.findByOrderId(orderId);
            orderProductDto.setOrderProductImageList(list);
            //产品信息
            ProductInfoDto productInfoDto = productInfoServiceApi.findById(orderProductDto.getProductId());
            if (productInfoDto != null) {
                orderProductDto.setProductName(productInfoDto.getName());
                orderProductDto.setProductImage(productInfoDto.getCover());
                orderProductDto.setContractUrl(productInfoDto.getOffice());
            }
            //订单地区信息
            if (orderProductDto.getCityCode() != null && !"".equals(orderProductDto.getCityCode())) {
                String cityName = areaServiceApi.queryParentsByCityCode(orderProductDto.getCityCode(), " ");
                orderProductDto.setCityName(cityName);
                List<AreaDto> areaList = areaServiceApi.queryParentsById(Long.parseLong(orderProductDto.getCityCode().toString()));
                for (AreaDto areaDto : areaList) {
                    if (areaDto.getLevel() != null) {
                        if (areaDto.getLevel().equals(1)) {
                            orderProductDto.setProvince(areaDto.getName());
                        }
                        if (areaDto.getLevel().equals(2)) {
                            orderProductDto.setCity(areaDto.getName());
                        }
                        if (areaDto.getLevel().equals(3)) {
                            orderProductDto.setDistrict(areaDto.getName());
                        }
                    }
                }
            }
        }
        OrderProductDetailResponse orderProductDetailResponse = DozerUtils.map(orderProductDto, OrderProductDetailResponse.class);
        List<OrderProjectRecordDto> orderProjectList = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(orderId);
        if (orderProjectList != null) {
            List<ProductContentResponse> packages = new ArrayList<>();//产品套餐内容
            List<ProductPromotionResponse> promotions = new ArrayList<>();//产品促销内容
            for (OrderProjectRecordDto pipd : orderProjectList) {
                if (pipd.getType().equals(0)) {
                    ProductContentResponse productContentResponse = new ProductContentResponse();
                    productContentResponse.setPromotionId(String.valueOf(pipd.getProjectId()));
                    productContentResponse.setPromotionName(pipd.getProjectName());
                    productContentResponse.setPromotionUnit(pipd.getProjectUnit());
                    productContentResponse.setPromotionValue(String.valueOf(pipd.getCount()));
                    packages.add(productContentResponse);
                }
                if (pipd.getType().equals(1)) {
                    ProductPromotionResponse productPromotionResponse = new ProductPromotionResponse();
                    productPromotionResponse.setPromotionId(String.valueOf(pipd.getProjectId()));
                    productPromotionResponse.setPromotionName(pipd.getProjectName());
                    productPromotionResponse.setPromotionUnit(pipd.getProjectUnit());
                    productPromotionResponse.setPromotionValue(String.valueOf(pipd.getCount()));
                    promotions.add(productPromotionResponse);
                }
            }
            orderProductDetailResponse.setPromotions(promotions);
            orderProductDetailResponse.setPackages(packages);
        }
        return orderProductDetailResponse;
    }

    public OrderProductDto getStatus(Long orderId) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderProductDto orderProductDto = orderProductServiceApi.findById(orderId);
        return orderProductDto;
    }


    /**
     * 查询产品订单列表
     *
     * @param pager
     * @param orderProductDto
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_PRODUCT)
    public PageInfo orderCouponsList(Pager pager, OrderProductDto orderProductDto) {
        PageInfo pageInfo = orderProductServiceApi.selectList(pager, orderProductDto);
        if (pageInfo != null && pageInfo.getList().size() > 0) {
            List<OrderProductDto> list = pageInfo.getList();
            for (OrderProductDto dto : list) {
                OrderYieldRatioDto yieldRatioDto = orderYieldRatioServiceApi.findOrderYieldRatioByOrderId(dto.getOrderId());
                if (yieldRatioDto != null) {
                    dto.setYieldRatioName("已选" + yieldRatioDto.getCashbackTime() + "个月返现率" + yieldRatioDto.getCashbackRatio() + "%");
                }
                ProductInfoDto productInfoDto = productInfoServiceApi.getProductProject(dto.getProductId());
                if (productInfoDto != null) {
                    dto.setProductImage(productInfoDto.getCover());
                }
            }
        }
        return pageInfo;
    }

    /**
     * 查看订单详情
     *
     * @param orderId
     * @return
     */
    public OrderCouponsDetailResponse orderCouponsDetail(Long orderId) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        OrderProductDto orderProductDto = orderProductServiceApi.findById(orderId);
        OrderCouponsDetailResponse response = DozerUtils.map(orderProductDto, OrderCouponsDetailResponse.class);
        if (orderProductDto != null) {
            List<OrderProjectRecordDto> list = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(orderId);
            response.setProjectList(DozerUtils.maps(list, OrderCouponsProjectResponse.class));
            OrderYieldRatioDto orderYieldRatioDto = orderYieldRatioServiceApi.findOrderYieldRatioByOrderId(orderId);
            response.setOrderYieldRatio(DozerUtils.map(orderYieldRatioDto, OrderYieldRatioResponse.class));
        }
        return response;
    }

    /**
     * 销售订单
     *
     * @param saleMemberId
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_COMMON)
    public SaleOrderResponse saleOrder(Long saleMemberId) {
        SaleOrderResponse saleOrderResponse = new SaleOrderResponse();

        //根据销售商会员id获取该销售商的券销售记录
//        这里先只拿龙之游产品的佣金
        List<MemberSaleLogDto> saleLogDtoList = memberSaleLogServiceApi.selectBySaleMemberId(saleMemberId);
        //获取总销售额和总佣金
        //总销售额
        BigDecimal saleMoney = new BigDecimal(0);

        //销售额
        BigDecimal oneSaleMoney = new BigDecimal(0);

        //代售额
        BigDecimal agentMoney = new BigDecimal(0);

        //总佣金
        BigDecimal commission = new BigDecimal(0);
        if (saleLogDtoList != null && saleLogDtoList.size() > 0) {
            for (MemberSaleLogDto mslDto : saleLogDtoList) {
                if (mslDto != null) {
                    if (mslDto.getCouponPrice() != null) {
                        //代售额
                        if (mslDto.getType().equals(0)) {
                            agentMoney = agentMoney.add(mslDto.getCouponPrice());
                            saleMoney = saleMoney.add(mslDto.getCouponPrice());
                        }
                        //销售额
                        if (mslDto.getType().equals(1)) {
                            oneSaleMoney = oneSaleMoney.add(mslDto.getCouponPrice());
                            saleMoney = saleMoney.add(mslDto.getCouponPrice());
                        }
                    }
                    if (mslDto.getCommission() != null) {
                        commission = commission.add(mslDto.getCommission());
                    }
                }
            }
        }
        //获取汽摩券列表
        List<MotorcycleDto> motorcycleDtoList = new ArrayList<>();
        MotorcycleDto motorcycleDto = new MotorcycleDto();
        motorcycleDto.setStatus(BusinessType.StatusEnum.ENABLED.getCode());
        motorcycleDto.setShelves(BusinessType.ShelfEnum.PUT.getK());
        PageInfo<MotorcycleDto> pageInfo = motorcycleServiceApi.selectList(null, motorcycleDto);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            motorcycleDtoList = pageInfo.getList();
        }
        saleOrderResponse.setAllSaleMoney(saleMoney);
        saleOrderResponse.setOneSaleMoney(oneSaleMoney);
        saleOrderResponse.setAgentMoney(agentMoney);
        saleOrderResponse.setAllCommission(commission);
        saleOrderResponse.setMotorcycleList(motorcycleDtoList);
        return saleOrderResponse;
    }


    /**
     * 销售订单列表
     *
     * @param saleMemberId
     * @param motorId
     * @param startTime
     * @param endTime
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_COMMON)
    public SaleOrderListResponse saleOrderList(Pager pager, Long saleMemberId, Long motorId, String startTime, String endTime, Integer status) {
        //返回结果集合
        SaleOrderListResponse saleOrderListResponse = new SaleOrderListResponse();
        //销售订单列表
        List<SaleOrderRecordResponse> saleOrderRecordResponseList = new ArrayList<>();
        //筛选结果集合
        FilterResponse filterResponse = new FilterResponse();

        //转变订单状态
        Integer minStatus = null;
        if (status != null) {
            if (status.equals(1)) {
                minStatus = OrderSatusDesEnum.MOTOR_COUPON_NO_PAY.getStatus();
            } else if (status.equals(2)) {
                minStatus = OrderSatusDesEnum.MOTOR_COUPON_COMPLETE.getStatus();
            } else if (status.equals(3)) {
                minStatus = OrderSatusDesEnum.MOTOR_COUPON_CAMP.getStatus();
            }
        }

        //根据saleMemberId获取shopId
        Long saleShopId = null;
        MemberUserDto memberUserDto = memberUserServiceApi.selectMemberByMemberId(saleMemberId);
        if (memberUserDto != null && memberUserDto.getAccount() != null) {
            StoreDto storeDto = new StoreDto();
            storeDto.setLegalContact(memberUserDto.getAccount());
            storeDto.setCategoryId(1100L);
            StoreDto storeDto1 = storeServiceApi.findStoreByContactAndCategory(storeDto);
            if (storeDto1 != null && storeDto1.getShopId() != null) {
                saleShopId = storeDto1.getShopId();
            }
        }
        //筛选销售量
        BigDecimal saleNumber = new BigDecimal(0);
        //总销售额
        BigDecimal saleMoney = new BigDecimal(0);

        //销售额
        BigDecimal oneSaleMoney = new BigDecimal(0);

        //代售额
        BigDecimal agentMoney = new BigDecimal(0);

        //总佣金
        BigDecimal commission = new BigDecimal(0);

        if (saleShopId != null) {

            //获取筛选结果集（总销售额）
            MotorSaleDTO motorSaleDTO = orderApi.selectMotorSale(saleShopId, motorId, startTime, endTime);
            if (motorSaleDTO != null) {
                if (motorSaleDTO.getSaleMoney() != null) {
                    saleMoney = saleMoney.add(motorSaleDTO.getSaleMoney());
                }
                if (motorSaleDTO.getCommission() != null) {
                    commission = commission.add(motorSaleDTO.getCommission());
                }
                if (motorSaleDTO.getSaleNumber() != null) {
                    saleNumber = saleNumber.add(motorSaleDTO.getSaleNumber());
                }
            }

            //获取代售额
            MotorSaleDTO motorcySaleDTO = orderApi.selectMotorSaleAgentMoney(saleShopId, motorId, startTime, endTime);
            if (motorcySaleDTO != null) {
                if (motorcySaleDTO.getAgentMoney() != null) {
                    agentMoney = agentMoney.add(motorcySaleDTO.getAgentMoney());
                }
            }

            //总销售额-代售额 = 自销额
            if (motorSaleDTO != null) {
                if (motorSaleDTO.getSaleMoney() != null) {
                    if (agentMoney != null) {
                        oneSaleMoney = motorSaleDTO.getSaleMoney().subtract(agentMoney);
                    } else {
                        oneSaleMoney = motorSaleDTO.getSaleMoney();
                    }
                } else {
                    saleMoney = agentMoney != null ? agentMoney : BigDecimal.ZERO;
                }
            }

            //获取销售订单列表
            PageInfo<MotorSaleDTO> pageInfo = orderApi.selectMotorSaleOrderList(pager, saleShopId, motorId, startTime, endTime, minStatus);
            if (pageInfo != null && pageInfo.getList().size() > 0) {
                List<MotorSaleDTO> motorSaleDTOList = pageInfo.getList();
                if (motorSaleDTOList != null && motorSaleDTOList.size() > 0) {
                    for (MotorSaleDTO motorSale : motorSaleDTOList) {
                        SaleOrderRecordResponse sorResponse = new SaleOrderRecordResponse();
                        sorResponse.setMotorName(motorSale.getMotorName());
                        sorResponse.setBanner(motorSale.getBanner());
                        sorResponse.setOrderStatus(status);
                        sorResponse.setNumber(motorSale.getNumber());
                        sorResponse.setOrderId(motorSale.getOrderId());
                        sorResponse.setAllMotorMoney(motorSale.getAllMotorMoney());
                        //对已支付状态的订单打标签（订单渠道（1-龙之游产品，2-销售商产品，3-两者都有））
                        if (status != null && status == 2) {
                            //保存自销代销列表(0-代销 1-自销)
                            List<Integer> typeList = new ArrayList<>();
                            //根据orderId查询出列表
                            MemberSaleLogDto memberSaleLogDto = new MemberSaleLogDto();
                            memberSaleLogDto.setOrderId(motorSale.getOrderId());
                            List<MemberSaleLogDto> memberSaleLogDtoList = memberSaleLogServiceApi.selectMemberSaleLog(memberSaleLogDto);
                            if (memberSaleLogDtoList != null && memberSaleLogDtoList.size() > 0) {
                                for (MemberSaleLogDto mslDto : memberSaleLogDtoList) {
                                    if (mslDto.getType() == 1) {
                                        typeList.add(1);
                                    } else {
                                        //当type为null和0时，是代销
                                        typeList.add(0);
                                    }
                                }
                                if (typeList.contains(0) && typeList.contains(1)) {
                                    sorResponse.setType(3);
                                } else if (!typeList.contains(0) && typeList.contains(1)) {
                                    sorResponse.setType(2);
                                } else {
                                    sorResponse.setType(1);
                                }
                            }
                        }
                        saleOrderRecordResponseList.add(sorResponse);
                    }
                }
            }
            //封装筛选结果集合
            if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
                String startTime1 = startTime.replaceAll("-", ".");
                String endTime1 = endTime.replaceAll("-", ".");
                String filterTime = startTime1 + "-" + endTime1;
                filterResponse.setFilterTime(filterTime);
            } else {
                filterResponse.setFilterTime("不限");
            }
            if (motorId != null) {
                MotorcycleDto motorcycleDto = motorcycleServiceApi.findById(motorId);
                if (motorcycleDto != null && motorcycleDto.getShortName() != null) {
                    filterResponse.setCouponName(motorcycleDto.getShortName());
                }
            } else {
                filterResponse.setCouponName("不限");
            }
        }
        filterResponse.setCommission(commission);
        filterResponse.setAgentMoney(agentMoney);
        filterResponse.setSaleMoney(saleMoney);
        filterResponse.setOneSaleMoney(oneSaleMoney);
        saleOrderListResponse.setSaleNumber(saleNumber);
        saleOrderListResponse.setStatus(status);
        saleOrderListResponse.setFilterResponse(filterResponse);
        saleOrderListResponse.setSaleOrderRecordResponseList(saleOrderRecordResponseList);
//        if ((startTime == null || startTime.equals("")) && (endTime == null || endTime.equals("")) && motorId == null) {
//            //没有做条件筛选时的销售量(即order_info表中的已支付的数据)
//            if (saleLogDtoList != null && saleLogDtoList.size() > 0) {
//                saleNumber = new BigDecimal(saleLogDtoList.size());
//            }
//        } else {
//            //做筛选条件时的销售量(即order_info表中的已支付的数据)
//            //保存订单号id列表
////            List<Long> motorIdList = new ArrayList<>();
//            String motorIds = "";
//            if (motorId != null) {
//                List<MotorcycleSpecDto> motorcycleSpecDtoList = motorcycleSpecServiceApi.selectByMotorcycleId(motorId);
//                if (motorcycleSpecDtoList != null && motorcycleSpecDtoList.size() > 0) {
//                    for (MotorcycleSpecDto msDto : motorcycleSpecDtoList) {
//                        if (msDto != null && msDto.getId() != null) {
//                            OrderInfoMotorCouponDTO oimcDto = new OrderInfoMotorCouponDTO();
//                            oimcDto.setSkuId(msDto.getId());
//                            oimcDto.setShopId(saleShopId);
//                            List<OrderInfoMotorCouponDTO> motorCouponDTOList = orderApi.selectOrderInfoMotorList(oimcDto);
//                            if (motorCouponDTOList != null && motorCouponDTOList.size() > 0) {
//                                for (OrderInfoMotorCouponDTO motorCouponDto : motorCouponDTOList) {
//                                    if (motorCouponDto != null && motorCouponDto.getOrderId() != null) {
////                                        motorIdList.add(motorCouponDto.getOrderId());
//                                        motorIds += (motorCouponDto.getOrderId() + ",");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                    //查询出订单列表
////                    for (Long orderId : motorIdList) {
//                        if (motorIds.length()>0) {
//                            motorIds = motorIds.substring(0, motorIds.length()-1);
//                        }
//                        OrderShowShopDTO orderShowShopDTO = new OrderShowShopDTO();
////                        orderShowShopDTO.setOrderId(orderId);
//                        orderShowShopDTO.setType(com.lzy.order.constants.OrderBusiConstants.OrderTypeEnum.MOTOR_COUPON.getType());
//                        //汽摩券是根据小状态来判断订单订单状态的（0-待支付 3-已完结（即已支付） 4-已关闭（即超时未支付））
//                        orderShowShopDTO.setMinStatus(OrderSatusDesEnum.MOTOR_COUPON_COMPLETE.getStatus());
//                        orderShowShopDTO.setShopId(saleShopId);
//                        List<OrderShowShopDTO> orderShowShopDTOList = new ArrayList<>();
//                        if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
//                            orderShowShopDTOList = orderApi.selectOrderListMotor(orderShowShopDTO, motorIds, startTime, endTime);
//                        } else {
//                            orderShowShopDTOList = orderApi.selectOrderListMotor(orderShowShopDTO, motorIds, null, null);
//                        }
//                        //查出的列表集合只有一个
//                        if (orderShowShopDTOList != null && orderShowShopDTOList.size() > 0) {
//                            for (OrderShowShopDTO ossDto : orderShowShopDTOList) {
//                                saleNumber = saleNumber.add(ossDto.getCount());
//
//                                //获取筛选结果数据
//                                MemberSaleLogDto memberSaleLogDto = new MemberSaleLogDto();
//                                memberSaleLogDto.setSaleMemberId(saleMemberId);
//                                memberSaleLogDto.setOrderId(ossDto.getOrderId());
//                                List<MemberSaleLogDto> memberSaleLogDtoList = memberSaleLogServiceApi.selectMemberSaleLog(memberSaleLogDto);
//                                if (memberSaleLogDtoList != null && memberSaleLogDtoList.size() > 0) {
//                                    for (MemberSaleLogDto mslDto : memberSaleLogDtoList) {
//                                        if (mslDto != null) {
//                                            //佣金额
//                                            if (mslDto.getCommission() != null) {
//                                                commission = commission.add(mslDto.getCommission());
//                                            }
//                                            if (mslDto.getCouponPrice() != null) {
//                                                //代售额
//                                                if (mslDto.getType().equals(0)) {
//                                                    agentMoney = agentMoney.add(mslDto.getCouponPrice());
//                                                    saleMoney = saleMoney.add(mslDto.getCouponPrice());
//                                                }
//                                                //销售额
//                                                if (mslDto.getType().equals(1)) {
//                                                    oneSaleMoney = oneSaleMoney.add(mslDto.getCouponPrice());
//                                                    saleMoney = saleMoney.add(mslDto.getCouponPrice());
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
////                }
//            } else {
//                //无motorId销售量
//                OrderShowShopDTO orderSSDto = new OrderShowShopDTO();
//                orderSSDto.setShopId(saleShopId);
//                orderSSDto.setMinStatus(OrderSatusDesEnum.MOTOR_COUPON_COMPLETE.getStatus());
//                orderSSDto.setType(com.lzy.order.constants.OrderBusiConstants.OrderTypeEnum.MOTOR_COUPON.getType());
//                List<OrderShowShopDTO> orderShowShopDTOList = new ArrayList<>();
//                if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
//                    orderShowShopDTOList = orderApi.selectOrderListMotor(orderSSDto, null, startTime, endTime);
//                } else {
//                    orderShowShopDTOList = orderApi.selectOrderListMotor(orderSSDto, null, null, null);
//                }
//                if (orderShowShopDTOList != null && orderShowShopDTOList.size() > 0) {
//                    for (OrderShowShopDTO orderSShopDto : orderShowShopDTOList) {
//                        if (orderSShopDto != null && orderSShopDto != null && orderSShopDto.getCount() != null) {
//                            saleNumber = saleNumber.add(orderSShopDto.getCount());
//                        }
//                    }
//                }
//            }
//        }
//
//        //筛选条件中有motorId
//        if (motorId != null) {
//            List<MotorcycleSpecDto> msDtoList = motorcycleSpecServiceApi.selectByMotorcycleId(motorId);
//            if (msDtoList != null && msDtoList.size() > 0) {
//                for (MotorcycleSpecDto msDto : msDtoList) {
//                    if (msDto != null) {
//                        OrderInfoMotorCouponDTO motorCouponDTO = new OrderInfoMotorCouponDTO();
//                        motorCouponDTO.setSkuId(msDto.getId());
//                        motorCouponDTO.setShopId(saleShopId);
//                        List<OrderInfoMotorCouponDTO> orderMotorCouponDTOList = orderApi.selectOrderInfoMotorList(motorCouponDTO);
//                        if (orderMotorCouponDTOList != null && orderMotorCouponDTOList.size() > 0) {
//                            for (OrderInfoMotorCouponDTO orderMotorDto : orderMotorCouponDTOList) {
//                                if (orderMotorDto != null && orderMotorDto.getOrderId() != null) {
////                                    orderIdList.add(orderMotorDto.getOrderId());
//                                    //有筛选时间条件
//                                    if (StringUtil.isNotEmpty(startTime)
//                                            && StringUtil.isNotEmpty(endTime)) {
//                                        SaleOrderRecordResponse saleOrderRecordResponse = getOrderInfo(orderMotorDto, minStatus, saleShopId, msDto, status, startTime, endTime);
//                                        if (saleOrderRecordResponse != null) {
//                                            saleOrderRecordResponseList.add(saleOrderRecordResponse);
//                                        }
//                                    } else {
//                                        //没有筛选时间条件
//                                        SaleOrderRecordResponse saleOrderRecordResponse = getOrderInfo(orderMotorDto, minStatus, saleShopId, msDto, status, null, null);
//                                        if (saleOrderRecordResponse != null) {
//                                            saleOrderRecordResponseList.add(saleOrderRecordResponse);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        } else {
//            //筛选条件中没有motorId
//            OrderInfoMotorCouponDTO mcDto = new OrderInfoMotorCouponDTO();
//            mcDto.setShopId(saleShopId);
//            List<OrderInfoMotorCouponDTO> orderMotorCouponDTOList = orderApi.selectOrderInfoMotorList(mcDto);
//            if (orderMotorCouponDTOList != null && orderMotorCouponDTOList.size() > 0) {
//                for (OrderInfoMotorCouponDTO orderMotorDto : orderMotorCouponDTOList) {
//                    if (orderMotorDto != null) {
//                        OrderShowShopDTO orderShowDto = new OrderShowShopDTO();
//                        orderShowDto.setType(com.lzy.order.constants.OrderBusiConstants.OrderTypeEnum.MOTOR_COUPON.getType());
//                        orderShowDto.setMinStatus(minStatus);
//                        orderShowDto.setShopId(saleShopId);
//                        orderShowDto.setOrderId(orderMotorDto.getOrderId());
//                        if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
//                            //有筛选时间条件
//                            SaleOrderRecordResponse saleOrderRecordResponse = getOrderInfo1(orderShowDto, status, orderMotorDto, startTime, endTime);
//                            if (saleOrderRecordResponse != null) {
//                                saleOrderRecordResponseList.add(saleOrderRecordResponse);
//                            }
//                        } else {
//                            //没有筛选时间
//                            SaleOrderRecordResponse saleOrderRecordResponse = getOrderInfo1(orderShowDto, status, orderMotorDto, null, null);
//                            if (saleOrderRecordResponse != null) {
//                                saleOrderRecordResponseList.add(saleOrderRecordResponse);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        //处理筛选时间
//        if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
//            String startTime1 = startTime.replaceAll("-", ".");
//            String endTime1 = endTime.replaceAll("-", ".");
//            String filterTime = startTime1 + "-" + endTime1;
//            filterResponse.setFilterTime(filterTime);
//        }
//        if (motorId != null) {
//            MotorcycleDto motorcycleDto = motorcycleServiceApi.findById(motorId);
//            if (motorcycleDto != null && motorcycleDto.getShortName() != null) {
//                filterResponse.setCouponName(motorcycleDto.getShortName());
//            }
//        }
//        filterResponse.setSaleMoney(saleMoney);
//        filterResponse.setOneSaleMoney(oneSaleMoney);
//        filterResponse.setAgentMoney(agentMoney);
//        filterResponse.setCommission(commission);
//        saleOrderListResponse.setSaleNumber(saleNumber);
//        saleOrderListResponse.setStatus(status);
//        if ((startTime == null || startTime.equals("")) && (endTime == null || endTime.equals(""))) {
//            filterResponse.setFilterTime("不限");
//        }
//        if (motorId == null) {
//            filterResponse.setCouponName("不限");
//        }
//        if ((startTime == null || startTime.equals("")) && (endTime == null || endTime.equals("")) && motorId == null) {
//            SaleOrderResponse saleOrderResponse = saleOrder(saleMemberId);
//            if (saleOrderResponse != null) {
//                filterResponse.setSaleMoney(saleOrderResponse.getAllSaleMoney());
//                filterResponse.setOneSaleMoney(saleOrderResponse.getOneSaleMoney());
//                filterResponse.setAgentMoney(saleOrderResponse.getAgentMoney());
//                filterResponse.setCommission(saleOrderResponse.getAllCommission());
//            }
//        }
//        saleOrderListResponse.setFilterResponse(filterResponse);
//        //代码分页
//        List<SaleOrderRecordResponse> saleOrderResponseList = new ArrayList<>();//分页后返回集合
//        if (saleOrderRecordResponseList != null && saleOrderRecordResponseList.size() > 0) {
//            if (pager == null) {
//                saleOrderListResponse.setSaleOrderRecordResponseList(saleOrderRecordResponseList);
//            } else if (pager != null && pager.getPageNum() == 1) {
//                for (int i = 0; i < pager.getPageSize() && i < saleOrderRecordResponseList.size(); i++) {
//                    if (saleOrderRecordResponseList.get(i) != null) {
//                        saleOrderResponseList.add(saleOrderRecordResponseList.get(i));
//                    }
//                }
//            } else {
//                for (int j = (pager.getPageNum() - 1) * pager.getPageSize();
//                     j < pager.getPageNum() * pager.getPageSize() && j < saleOrderRecordResponseList.size();
//                     j++) {
//                    if (saleOrderRecordResponseList.get(j) != null) {
//                        saleOrderResponseList.add(saleOrderRecordResponseList.get(j));
//                    }
//                }
//            }
//        }
//        List<Integer> typeList = new ArrayList<>();
//        //对已支付的订单打标签（订单渠道（0-龙之游产品，1-销售商产品，2-两者都有））
//        if (status.equals(2)) {
//            if (saleOrderResponseList != null && saleOrderResponseList.size() > 0) {
//                for (SaleOrderRecordResponse sorResponse : saleOrderRecordResponseList) {
//                    if (sorResponse != null && sorResponse.getOrderId() != null) {
//                        MemberSaleLogDto mslDto = new MemberSaleLogDto();
//                        mslDto.setOrderId(sorResponse.getOrderId());
//                        List<MemberSaleLogDto> mslDtoList = memberSaleLogServiceApi.selectMemberSaleLog(mslDto);
//                        if (mslDtoList != null && mslDtoList.size() > 0) {
//                            for (MemberSaleLogDto msl : mslDtoList) {
//                                if (msl != null && msl.getType() != null) {
//                                    typeList.add(msl.getType());
//                                }
//                            }
//                            if (typeList.contains(0) && typeList.contains(1)) {
//                                sorResponse.setType(3);
//                            } else if (!typeList.contains(0) && typeList.contains(1)) {
//                                sorResponse.setType(2);
//                            } else {
//                                sorResponse.setType(1);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        if (saleOrderResponseList != null) {
//            saleOrderListResponse.setSaleOrderRecordResponseList(saleOrderResponseList);
//        }
        return saleOrderListResponse;
    }

    /**
     * 获取销售订单详情
     *
     * @param orderId
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_COMMON)
    public SaleOrderDetailResponse saleOrderDetail(Long orderId) {
        SaleOrderDetailResponse saleOrderDetailResponse = new SaleOrderDetailResponse();
        OrderShowShopDTO ossDto = new OrderShowShopDTO();
        ossDto.setOrderId(orderId);
        PageInfo<OrderShowShopDTO> pageInfo = orderApi.selectOrderList(null, ossDto, null, null, null);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            OrderShowShopDTO orderShowShopDTO = pageInfo.getList().get(0);
            saleOrderDetailResponse.setOrderId(orderShowShopDTO.getOrderId());
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String orderTime = df.format(orderShowShopDTO.getCreateTime());
            saleOrderDetailResponse.setOrderTime(orderTime);
            if (orderShowShopDTO.getMinStatus() != null) {
                if (orderShowShopDTO.getMinStatus().equals(OrderSatusDesEnum.MOTOR_COUPON_NO_PAY.getStatus())) {
                    saleOrderDetailResponse.setStatus(1);
                } else if (orderShowShopDTO.getMinStatus().equals(OrderSatusDesEnum.MOTOR_COUPON_COMPLETE.getStatus())) {
                    saleOrderDetailResponse.setStatus(2);
                } else if (orderShowShopDTO.getMinStatus().equals(OrderSatusDesEnum.MOTOR_COUPON_CAMP.getStatus())) {
                    saleOrderDetailResponse.setStatus(3);
                }
            }
            saleOrderDetailResponse.setCouponType(4);
            saleOrderDetailResponse.setOrderAmount(orderShowShopDTO.getOrderAmount());
            saleOrderDetailResponse.setNumber(orderShowShopDTO.getCount() != null ? orderShowShopDTO.getCount().intValue() : 0);
            //根据用户id获取下单人姓名
            MemberUserDto memberUserDto = memberUserServiceApi.selectMemberById(orderShowShopDTO.getUserId());
            if (memberUserDto != null && memberUserDto.getName() != null && !memberUserDto.getName().equals("")) {
                saleOrderDetailResponse.setName(memberUserDto.getName());
            }
            OrderInfoMotorCouponDTO oimcDto = new OrderInfoMotorCouponDTO();
            oimcDto.setOrderId(orderShowShopDTO.getOrderId());
            List<OrderInfoMotorCouponDTO> oimcList = orderApi.selectOrderInfoMotorList(oimcDto);
            if (oimcList != null && oimcList.size() > 0) {
                OrderInfoMotorCouponDTO motorCouponDTO = oimcList.get(0);
                if (motorCouponDTO != null && motorCouponDTO.getSkuId() != null) {
                    MotorcycleSpecDto specDto = motorcycleSpecServiceApi.findById(motorCouponDTO.getSkuId());
                    if (specDto != null && specDto.getMotorcycleId() != null) {
                        MotorcycleDto motorcycleDto = motorcycleServiceApi.findById(specDto.getMotorcycleId());
                        if (motorcycleDto != null && motorcycleDto.getShortName() != null && !motorcycleDto.getShortName().equals("")) {
                            saleOrderDetailResponse.setCouponName(motorcycleDto.getShortName());
                        }
                    }
                }
            }
        }
        return saleOrderDetailResponse;
    }

    /**
     * 销售补贴明细
     *
     * @param type   （1-套餐补贴  2-销售补贴 3-代理销售（如 一区总代））
     * @param status 1-已补贴 2-限制期内
     * @return
     */
    @DataSource(name = DataSource.DATASOURCE_PRODUCT)
    public List<SaleSubsidyResponse> subsidy(Pager pager, Long saleMemberId, Integer type, Integer status) {
        List<SaleSubsidyResponse> saleSubsidyResponseList = new ArrayList<>();
        //1-可限制  3-可提现
        Integer subsidyStatus = null;
        if (status == 1) {
            subsidyStatus = 3;
        } else if (status == 2) {
            subsidyStatus = 1;
        }
        //类型（1-套餐补贴，2-佣金，3-卖券收益）
        String typeStr = "";
        if (type == 1) {
            typeStr = typeStr + "1";
        } else if (type == 2) {
            typeStr = typeStr + "2,3";
        } else if (type == 3) {
            typeStr = typeStr + "4";
        }
        PageInfo<CouponProfitRecordDto> pageInfo = couponProfitRecordServiceApi.selectListByType(pager, saleMemberId, typeStr, subsidyStatus);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            List<CouponProfitRecordDto> couponProfitRecordDtoList = pageInfo.getList();
            for (CouponProfitRecordDto cprDto : couponProfitRecordDtoList) {
                if (cprDto != null) {
                    SaleSubsidyResponse saleSubsidyResponse = new SaleSubsidyResponse();
                    if (cprDto.getType() == 1) {
                        saleSubsidyResponse.setDetailName("套餐补贴");
                    }
                    if (cprDto.getType() == 2) {
                        saleSubsidyResponse.setDetailName("代理销售佣金");
                    }
                    if (cprDto.getType() == 3) {
                        saleSubsidyResponse.setDetailName("自有卡券销售");
                    }
                    if (cprDto.getType() == 4) {
                        saleSubsidyResponse.setDetailName("佣金");
                    }
                    saleSubsidyResponse.setIncomeMoney("+" + cprDto.getAmount().toString());
                    if (cprDto.getIncomeTime() != null) {
                        //type : 1-套餐补贴  2-销售补贴 3-代理销售
                        //status : 1-已补贴 2-限制期内
                        String incomeTime = cprDto.getIncomeTime().substring(0, 10);
                        String incomeTime1 = cprDto.getIncomeTime().substring(0, cprDto.getIncomeTime().length() - 2);
                        if (type == 1 && status == 2) {
                            saleSubsidyResponse.setIncomeTime("补贴日期 " + incomeTime);
                        } else if (type == 2 && status == 2) {
                            saleSubsidyResponse.setIncomeTime("入账日期 " + incomeTime);
                        } else if (type == 2 && status == 1) {
                            saleSubsidyResponse.setIncomeTime(incomeTime1);
                        } else if (type == 1 && status == 1) {
                            saleSubsidyResponse.setIncomeTime(incomeTime1);
                        } else if (type == 3 && status == 1) {
                            saleSubsidyResponse.setIncomeTime("入账日期 " + incomeTime);
                        } else if (type == 3 && status == 2) {
                            saleSubsidyResponse.setIncomeTime(incomeTime);
                        }
                    }
                    saleSubsidyResponseList.add(saleSubsidyResponse);
                }
            }
        }
        return saleSubsidyResponseList;
    }


    public SaleOrderRecordResponse getOrderInfo(OrderInfoMotorCouponDTO orderMotorDto, Integer minStatus, Long saleShopId,
                                                MotorcycleSpecDto msDto, Integer status, String startTime, String endTime) {
        OrderShowShopDTO ossDto = new OrderShowShopDTO();
        ossDto.setShopId(saleShopId);
        ossDto.setMinStatus(minStatus);
        ossDto.setType(com.lzy.order.constants.OrderBusiConstants.OrderTypeEnum.MOTOR_COUPON.getType());
        ossDto.setOrderId(orderMotorDto.getOrderId());
        List<OrderShowShopDTO> orderShowShopDTOList = orderApi.selectOrderListMotor(ossDto, null, startTime, endTime);
        if (orderShowShopDTOList != null && orderShowShopDTOList.size() > 0) {
            if (orderShowShopDTOList.get(0) != null) {
                OrderShowShopDTO showShopDTO = orderShowShopDTOList.get(0);
                SaleOrderRecordResponse saleOrderRecordResponse = new SaleOrderRecordResponse();
                saleOrderRecordResponse.setOrderId(showShopDTO.getOrderId());
                saleOrderRecordResponse.setAllMotorMoney(showShopDTO.getOrderAmount());
                saleOrderRecordResponse.setNumber(showShopDTO.getCount().intValue());
                saleOrderRecordResponse.setOrderStatus(status);
                //获取卡券类型信息
                MotorcycleDto motorcycleDto = motorcycleServiceApi.selectMotorcycleDtoByMotorcycleId(msDto.getMotorcycleId());
                if (motorcycleDto != null) {
                    saleOrderRecordResponse.setBanner(motorcycleDto.getBanner());
                    saleOrderRecordResponse.setMotorName(motorcycleDto.getShortName());
                }
                return saleOrderRecordResponse;
            }
        }
        return null;
    }

    public SaleOrderRecordResponse getOrderInfo1(OrderShowShopDTO orderShowDto, Integer status,
                                                 OrderInfoMotorCouponDTO orderMotorDto,
                                                 String startTime, String endTime) {
        List<OrderShowShopDTO> orderShowShopDTOList = orderApi.selectOrderListMotor(orderShowDto, null, startTime, endTime);
        if (orderShowShopDTOList != null && orderShowShopDTOList.size() > 0) {
            if (orderShowShopDTOList.get(0) != null) {
                OrderShowShopDTO orderInfoDto = orderShowShopDTOList.get(0);
                SaleOrderRecordResponse saleOrderRecordResponse = new SaleOrderRecordResponse();
                saleOrderRecordResponse.setOrderId(orderInfoDto.getOrderId());
                saleOrderRecordResponse.setAllMotorMoney(orderInfoDto.getOrderAmount());
                saleOrderRecordResponse.setNumber(orderInfoDto.getCount().intValue());
                saleOrderRecordResponse.setOrderStatus(status);
                //获取卡券类型信息
                MotorcycleSpecDto specDto = motorcycleSpecServiceApi.selectBySpecId(orderMotorDto.getSkuId());
                if (specDto != null && specDto.getMotorcycleId() != null) {
                    MotorcycleDto motorcycleDto = motorcycleServiceApi.selectMotorcycleDtoByMotorcycleId(specDto.getMotorcycleId());
                    if (motorcycleDto != null) {
                        saleOrderRecordResponse.setBanner(motorcycleDto.getBanner());
                        saleOrderRecordResponse.setMotorName(motorcycleDto.getShortName());
                    }
                }
                return saleOrderRecordResponse;
            }
        }
        return null;
    }

    /**
     * 获取直接下级代理商
     *
     * @param memberId
     * @return
     */
    public AgentResponse getAgentList(Pager pager, Long memberId) {
        AgentResponse agentResponse = new AgentResponse();
        List<AgentListResponse> agentListResponseList = new ArrayList<>();
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        MemberUserDto memberUserDto = memberUserServiceApi.selectMemberByMemberId(memberId);
        if (memberUserDto != null && memberUserDto.getAccount() != null) {
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
            ProductUserDto productUserDto = productUserServiceApi.queryByPhone(memberUserDto.getAccount());
            if (productUserDto != null) {
                ProductUserDto puDto = new ProductUserDto();
                puDto.setUserId(productUserDto.getId());
                PageInfo<ProductUserDto> pageInfo = productUserServiceApi.queryUserList(pager, puDto);
                List<ProductUserDto> productUserDtoList = pageInfo.getList();
                if (productUserDtoList != null && productUserDtoList.size() > 0) {
                    for (ProductUserDto userDto : productUserDtoList) {
                        AgentListResponse agentListResponse = new AgentListResponse();
                        if (userDto.getName() != null) {
                            agentListResponse.setName(userDto.getName());
                        }
                        if (userDto.getPhone() != null) {
                            agentListResponse.setPhone(userDto.getPhone());
                        }
                        if (userDto.getId() != null) {
                            agentListResponse.setId(String.valueOf(userDto.getId()));
                        }
                        agentListResponseList.add(agentListResponse);
                    }
                    agentResponse.setNumber(productUserDtoList.size());
                }
            }
            DataSourceHolder.clearDataSource();
        }
        DataSourceHolder.clearDataSource();
        agentResponse.setAgentListResponseList(agentListResponseList);
        return agentResponse;
    }

    /**
     * 根据userId获取销售列表
     */
    public AgentSaleRecordResponse getSaleList(Pager pager, Long userId) {
        AgentSaleRecordResponse saleRecordResponse = new AgentSaleRecordResponse();
        List<SaleRecordResponse> saleRecordResponseList = new ArrayList<>();
        ProductUserDto userDto = productUserServiceApi.findById(userId);
        if (userDto != null) {
            if (userDto.getPhone() != null) {
                saleRecordResponse.setPhone(userDto.getPhone());
            }
            if (userDto.getName() != null) {
                saleRecordResponse.setName(userDto.getName());
            }
            if (userDto.getAgentNumber() != null && !userDto.equals("")) {
                saleRecordResponse.setAgentNumber("No." + userDto.getAgentNumber());
            }
        }
        AgentOrderInfoDto orderInfoDto = new AgentOrderInfoDto();
        orderInfoDto.setUserId(userId);
        PageInfo<AgentOrderSalesRecordDto> pageInfo = agentOrderInfoServiceApi.statisticalSalesRecord(pager, orderInfoDto);
        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            List<AgentOrderSalesRecordDto> agentOrderSalesRecordDtoList = pageInfo.getList();
            for (AgentOrderSalesRecordDto aosrDto : agentOrderSalesRecordDtoList) {
                if (aosrDto != null) {
                    SaleRecordResponse recordResponse = new SaleRecordResponse();
                    if (!BigDecimalUtil.isZeroOrNull(aosrDto.getAmountTotal())) {
                        recordResponse.setCommission(aosrDto.getAmountTotal());
                    }
                    if (!BigDecimalUtil.isZeroOrNull(aosrDto.getMoneyCountTotal())) {
                        recordResponse.setSaleMoney(aosrDto.getMoneyCountTotal());
                    }
                    if (aosrDto.getStatisticalMonth() != null && !aosrDto.getStatisticalMonth().equals("")) {
                        recordResponse.setTime(aosrDto.getStatisticalMonth().substring(0, 4) + "年" + aosrDto.getStatisticalMonth().substring(5, 7) + "月");
                    }
                    saleRecordResponseList.add(recordResponse);
                }
            }
            saleRecordResponse.setSaleRecordResponseList(saleRecordResponseList);
        }
        return saleRecordResponse;
    }

    /**
     * 代理商销售记录
     */
    public AgentRecordResponse queryAgentSaleRecordList(Pager pager, Long userId, Integer type, String timeStr) {
        AgentRecordResponse agentRecordResponse = new AgentRecordResponse();
        List<AgentSaleDetailResponse> agentSaleDetailResponseList = new ArrayList<>();
        if (type != null) {
            String timeString = "";
            if (type == 1) {
                timeString = timeStr + "年";
            }
            if (type == 2) {
                timeString = timeStr.substring(0, 4) + "年" + timeStr.substring(5, 7) + "月";
            }
            agentRecordResponse.setTimeStr(timeString);
        }
        BigDecimal allSaleAmount = new BigDecimal(0);
        BigDecimal allCommission = new BigDecimal(0);
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        MemberUserDto memberUserDto = memberUserServiceApi.selectMemberByMemberId(userId);
        if (memberUserDto != null && memberUserDto.getAccount() != null) {
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
            ProductUserDto puDto = productUserServiceApi.queryByPhone(memberUserDto.getAccount());
            if (puDto != null) {
                ProductUserDto productUserDto = new ProductUserDto();
                productUserDto.setUserId(puDto.getId());
                PageInfo<ProductUserDto> pageInfo = productUserServiceApi.queryAgents(pager, productUserDto);
                if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
                    List<ProductUserDto> userDtoList = pageInfo.getList();
                    String idList = "";
                    //下级代理商id列表
                    List<Long> userIdList = new ArrayList<>();
                    //有订单的下级代理商id列表
                    List<Long> orderUserIdList = new ArrayList<>();
                    for (ProductUserDto dto : userDtoList) {
                        if (dto != null && dto.getId() != null) {
                            idList = idList + dto.getId() + ",";
                            userIdList.add(dto.getId());
                        }
                    }
                    List<AgentOrderSalesRecordDto> salesRecordDtoList = agentOrderInfoServiceApi.statisticalSalesRecordByCondition(idList.substring(0, idList.length() - 1), type, timeStr);
                    if (salesRecordDtoList != null && salesRecordDtoList.size() > 0) {
                        for (AgentOrderSalesRecordDto aosrDto : salesRecordDtoList) {
                            if (aosrDto != null) {
                                AgentSaleDetailResponse agentSaleDetailResponse = new AgentSaleDetailResponse();
                                if (!BigDecimalUtil.isZeroOrNull(aosrDto.getMoneyCountTotal())) {
                                    agentSaleDetailResponse.setSaleMoney(aosrDto.getMoneyCountTotal());
                                    allSaleAmount = allSaleAmount.add(aosrDto.getMoneyCountTotal());
                                }
                                if (!BigDecimalUtil.isZeroOrNull(aosrDto.getAmountTotal())) {
                                    agentSaleDetailResponse.setCommission(aosrDto.getAmountTotal());
                                    allCommission = allCommission.add(aosrDto.getAmountTotal());
                                }
                                if (aosrDto.getUserId() != null) {
                                    orderUserIdList.add(aosrDto.getUserId());
                                    ProductUserDto userDto = productUserServiceApi.findById(aosrDto.getUserId());
                                    if (userDto != null) {
                                        if (userDto.getRealName() != null) {
                                            agentSaleDetailResponse.setName(userDto.getRealName());
                                        }
                                        if (userDto.getPhone() != null) {
                                            agentSaleDetailResponse.setPhone(userDto.getPhone());
                                        }
                                    }
                                }
                                agentSaleDetailResponseList.add(agentSaleDetailResponse);
                            }
                        }
                        agentRecordResponse.setAllSaleAmount(allSaleAmount);
                        agentRecordResponse.setAllCommission(allCommission);
                    }
                    for (Long l : userIdList) {
                        if (!orderUserIdList.contains(l)) {
                            AgentSaleDetailResponse SaleDetailResponse = new AgentSaleDetailResponse();
                            SaleDetailResponse.setSaleMoney(new BigDecimal(0));
                            SaleDetailResponse.setCommission(new BigDecimal(0));
                            ProductUserDto user = productUserServiceApi.findById(l);
                            if (user != null) {
                                if (user.getRealName() != null) {
                                    SaleDetailResponse.setName(user.getRealName());
                                }
                                if (user.getPhone() != null) {
                                    SaleDetailResponse.setPhone(user.getPhone());
                                }
                            }
                            agentSaleDetailResponseList.add(SaleDetailResponse);
                        }
                    }

                }
            }
            DataSourceHolder.clearDataSource();
        }
        DataSourceHolder.clearDataSource();

        agentRecordResponse.setAgentSaleDetailResponseList(agentSaleDetailResponseList);
        return agentRecordResponse;
    }
}
